﻿using System.Collections.Specialized;
using System.Runtime.Serialization;

namespace Mvc.XForms.UI {
	[DataContract]
	public abstract class PagedList<T> : GridItems<T>, IPagedList<T> {
		// Empty constructor so inherited objects can determine init order
		protected PagedList() { }

		protected PagedList(NameValueCollection collection, string pageIndexKey, int pageSize)
			: this(new PagedParameters(collection, pageIndexKey, pageSize)) { }

		protected PagedList(IPagedParameters gridParams) {
			InitWithParams(gridParams);
		}

		protected PagedList(int pageIndex, int pageSize) {
			Init(pageIndex, pageSize);
		}

		protected void InitWithParams(IPagedParameters gridParams) {
			SetParameters(gridParams);
			Init(gridParams.PageIndex, gridParams.PageSize);
		}

		protected void Init(int pageIndex, int pageSize) {
			PageIndex = pageIndex;
			PageSize = pageSize;
			TotalCount = GetTotalCount();
			PageCount = this.GetPageCount();

			// Sanitise page index
			PageIndex = this.GetValidPageIndex(pageIndex);

			ApplyPaging();
		}

		public void SetParameters(IPagedParameters gridParams) {
			PageIndex = gridParams.PageIndex;
			PageSize = gridParams.PageSize;
			PageIndexKey = gridParams.PageIndexKey;
		}

		protected abstract int GetTotalCount();
		protected abstract void ApplyPaging();

		[DataMember]
		public string PageIndexKey { get; protected set; }
		[DataMember]
		public int PageIndex { get; protected set; }
		[DataMember]
		public int PageSize { get; protected set; }
		[DataMember]
		public int PageCount { get; protected set; }
		[DataMember]
		public int TotalCount { get; protected set; }

		public bool IsPrevious {
			get { return this.GetIsPrevious(); }
		}

		public bool IsNext {
			get { return this.GetIsNext(); }
		}
	}
}